package com.cps116.friendstracker;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.cps116.parcelables.Coordinate;
import com.cps116.parcelables.LocationTraceList;
import com.cps116.parcelables.MapParcelableData;
import com.cps116.resource.HttpResponseDecoder;
import com.easy.facebook.android.apicall.FQL;

import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;

public class QueryActivity extends TabActivity implements OnSharedPreferenceChangeListener{

	private SharedPreferences prefs;
	
	static final String[] OPTIONS = new String[] {
		"Find Friends Within __ Distance",
		"Find My Check-in Locations",
		"Find the Locations that my Friend has Checked in to",
		"Find Friends that have Checked into Locations that I have Checked in to",
		"Plot My Boundaries",
		"Plot Friend's Boundaries"
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.queryactivity_layout);

		//set up the shared application preferences..
		prefs = PreferenceManager.getDefaultSharedPreferences(this); 
		prefs.registerOnSharedPreferenceChangeListener(this); 

		//tab-related setup
		TabHost mTabHost = getTabHost();

		ListView list=(ListView)findViewById(R.id.query_activity_query_listview);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, OPTIONS);
		list.setAdapter(adapter);
		
		ListView history_list=(ListView)findViewById(R.id.query_activity_query_history_listview);


		
		try {
			String myUID = ((FriendsTrackerApplication) getApplication()).getFacebookUserId();
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://dbcourse.cs.duke.edu/tnd6/FFQueries/returnuserqueries.php");

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		    nameValuePairs.add(new BasicNameValuePair("userid", myUID));
		    
		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        HttpResponse response = httpclient.execute(httppost);
	        
	        String[] query_history = HttpResponseDecoder.getResponseBody(response).split(";");
			ArrayAdapter<String> history_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, query_history);
			history_list.setAdapter(history_adapter);
	        
		}catch(Exception e)
		{
			//insert stack trace if necessary
		}


		Resources res = getResources();
		mTabHost.addTab(mTabHost.newTabSpec("Tab 1").setIndicator("Query", res.getDrawable(android.R.drawable.ic_menu_help)).setContent(R.id.query_activity_query_listview));
		mTabHost.addTab(mTabHost.newTabSpec("Tab 2").setIndicator("Query History", res.getDrawable(android.R.drawable.ic_menu_agenda)).setContent(R.id.query_activity_query_history_listview));

		mTabHost.setCurrentTab(0);

		list.setOnItemClickListener(new ListOptionSelector(this));
	}

	private class ListOptionSelector implements OnItemClickListener
	{
		Context context;

		ListOptionSelector(Context c)
		{
			context = c;
		}


		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			String myUID = ((FriendsTrackerApplication) getApplication()).getFacebookUserId();
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://dbcourse.cs.duke.edu/tnd6/FFQueries/insertquery.php");

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		    nameValuePairs.add(new BasicNameValuePair("querytime", new java.util.Date().toString()));
		    Log.d("FriendsTrackerApplication",new java.util.Date().toString());
			    
			switch(position)
			{
			case 0:
				startActivity(new Intent(context, QueryActivity_FriendsWithinDistanceActivity.class));
				nameValuePairs.add(new BasicNameValuePair("querytype", "Find Friends Within __ Distance"));
				break;
			case 1:
				startActivity(new Intent(context, QueryActivity_MyCheckinsActivity.class));
				nameValuePairs.add(new BasicNameValuePair("querytype", "Find My Check-in Locations"));
				break;
			case 2:
				startActivity(new Intent(context, QueryActivity_CheckinsOfFriendActivity.class));
				nameValuePairs.add(new BasicNameValuePair("querytype", "Find the Locations that my Friend has Checked in to"));
				break;
			case 3:
				startActivity(new Intent(context, QueryActivity_FriendsFrequentWhereIFrequentActivity.class));
				nameValuePairs.add(new BasicNameValuePair("querytype", "Find Friends that have Checked into Locations that I have Checked in to"));
				break;
			case 4:
				//no need to pull up another layout so we can run this query straight out of the QueryActivity class
				runPlotMyBoundaries();
				nameValuePairs.add(new BasicNameValuePair("querytype", "Plot My Boundaries"));
				break;
			case 5:
				startActivity(new Intent(context, QueryActivity_PlotPathOfFriendActivity.class));
				nameValuePairs.add(new BasicNameValuePair("querytype", "Plot Friends Boundaries"));
				break;
			}

			Log.d("userid",myUID);
		    nameValuePairs.add(new BasicNameValuePair("userid", myUID));
			try {
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        HttpResponse response = httpclient.execute(httppost);
		    } catch (Exception e) {
		        // TODO Auto-generated catch block
		    }
		}

	}


	private void runPlotMyBoundaries()
	{
		FQL facebookFQL = ((FriendsTrackerApplication) getApplication()).getFacebookFQL();

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://dbcourse.cs.duke.edu/tnd6/FFQueries/pulllocationinfo.php");

		try
		{
			String myUID = ((FriendsTrackerApplication) getApplication()).getFacebookUserId();
			String myName = facebookFQL.fqlQuery("SELECT name FROM user WHERE uid = " + myUID);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("userid", myUID));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));					
			HttpResponse response = httpclient.execute(httppost);
			String locationsString = HttpResponseDecoder.getResponseBody(response);

			//if the user has no location information in the database, we'll catch those and display another screen that just says "No Location Information in Database"
			if(locationsString.equals(";") || locationsString.equals(""))
			{
				Log.d("No Location Information", "No Location Information in Database");
				startActivity(new Intent(this, QueryActivity_PlotPathOfFriendActivity_NoLocations.class));
			}
			else 
			{

				Intent mapIntent = new Intent(this, FriendsFinderMapActivity.class);
				List<MapParcelableData> mapData = new ArrayList<MapParcelableData>();
				List<Coordinate> coords = new ArrayList<Coordinate>();

				Pattern coordsPattern = Pattern.compile("(.+?);(.+?);(.+?);(.+?);");
				Matcher coordsMatcher = coordsPattern.matcher(locationsString);

				while(coordsMatcher.find())
				{
					//systematically adds the coordinates to the list
					coords.add(new Coordinate(Double.parseDouble(coordsMatcher.group(4)), Double.parseDouble(coordsMatcher.group(3))));
				}

				long updateTime = 10000;
				boolean toUpdate = true;

				MapParcelableData inputData = new MapParcelableData(coords, toUpdate, myName, myUID, updateTime);
				mapData.add(inputData);

				LocationTraceList parcelableList = new LocationTraceList(mapData);
				mapIntent.putExtra("overlays", parcelableList);
				mapIntent.putExtra("update_time", updateTime);
				mapIntent.putExtra("need_to_update", toUpdate);

				startActivity(mapIntent);

			}
		}
		catch(Exception e)
		{
			Log.d("EXCEPTION", "EXCEPTION");
			e.printStackTrace();
		}
	}



	//create the option menu 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.friendstracker_menu, menu);
		return true;
	}

	//switching between different views

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {                              // 
		case R.id.menuOptionProfile:
			startActivity(new Intent(this, ProfileActivity.class));  // 
			break;
		case R.id.menuOptionMap:
			startActivity(new Intent(this, FriendsFinderMapActivity.class));
			break;
		case R.id.menuOptionQuery:
			startActivity(new Intent(this, QueryActivity.class));
			break;
		case R.id.menuOptionLogOut:
			((FriendsTrackerApplication) getApplication()).logoutFacebook();
			startActivity(new Intent(this, FacebookConnect.class));
			break;
		}

		return true;  // 
	}



	public void onSharedPreferenceChanged(SharedPreferences preferences, String string) {
		//be able to update the user's preference

	}






}
